package cn.wzptsoft.tinymallbe.service;

import cn.wzptsoft.tinymallbe.entity.Address;
import cn.wzptsoft.tinymallbe.repository.AddressRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class AddressService {
    @Autowired
    private AddressRepository addressRepository;


    public List<Address> addres(Integer userid) {
        List<Address> byId = addressRepository.findByUserId(userid);
        if (byId.isEmpty()){
            return null;
        }else {
            return byId;
        }
    }

    public Address add(Address address) {
        Address aa = new Address();
//        用户id先固定，之后改
        aa.setUserId(1);
        aa.setName(address.getName());
        aa.setTel(address.getTel());
        aa.setArea(address.getArea());
        aa.setDetail(address.getDetail());
        return addressRepository.save(aa);
    }

    public Address updata(Address form) {
        Optional<Address> byId = addressRepository.findById(form.getId());
        if (byId.isPresent()){
            Address a1=byId.get();
            a1.setId(byId.get().getId());
            a1.setName(form.getName());
            a1.setTel(form.getTel());
            a1.setArea(form.getArea());
            a1.setDetail(form.getDetail());
            a1.setIsDefault(form.getIsDefault());
            return addressRepository.save(a1);
        }else {
            return null;
        }
    }


    public String delete(Long id) {
        Optional<Address> byId = addressRepository.findById(id);
        if (byId.isPresent()){
            addressRepository.deleteById(id);
            return "删除成功";
        }else {
            return "删除失败";
        }
    }
}
